// 初始化数据库（创建对象存储）
export function initDB(dbName = "AppStorage", storeName = "namedCollections") {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open(dbName, 1);

    request.onupgradeneeded = (event) => {
      const db = event.target.result;
      if (!db.objectStoreNames.contains(storeName)) {
        // 创建对象存储空间，主键为 name
        db.createObjectStore(storeName, { keyPath: "name" });
      }
    };
    request.onsuccess = () => resolve(request.result);
    request.onerror = (err) => reject(err);
  });
}

// 核心存储方法（存储/更新整个数组）
export async function addData(collectionName, dataArray) {
  const db = await initDB();
  const transaction = db.transaction("namedCollections", "readwrite");
  const store = transaction.objectStore("namedCollections");

  return new Promise((resolve, reject) => {
    // 存储结构：{ name: "list", data: [...] }
    const request = store.put({
      name: collectionName,
      data: dataArray,
      updatedAt: new Date().getTime(),
    });

    request.onsuccess = () => resolve();
    request.onerror = (err) => reject(err);
  });
}

// 获取指定名称的数组数据
export async function getData(collectionName) {
  const db = await initDB();
  const transaction = db.transaction("namedCollections");
  const store = transaction.objectStore("namedCollections");

  return new Promise((resolve, reject) => {
    const request = store.get(collectionName);

    request.onsuccess = () => resolve(request.result?.data || []);
    request.onerror = (err) => reject(err);
  });
}

// 删除指定名称的存储
export async function deleteData(collectionName) {
  const db = await initDB();
  const transaction = db.transaction("namedCollections", "readwrite");
  const store = transaction.objectStore("namedCollections");

  return new Promise((resolve, reject) => {
    const request = store.delete(collectionName);

    request.onsuccess = () => resolve();
    request.onerror = (err) => reject(err);
  });
}

// 追加数据到现有集合
export async function appendData(collectionName, newItems) {
  const existingData = await getData(collectionName);
  return addData(collectionName, [...existingData, ...newItems]);
}
